package com.example.zt.musicdemo02;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;

public class MusicService extends Service {
    private MediaPlayer mediaPlayer;
    private String mp3path="";
    private boolean isPause = false;
    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        mp3path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mp3/";
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action  =intent.getStringExtra("action");
        String music = intent.getStringExtra("music");
        switch (action){
            case "play":
                try {
                    play(music);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "pause":
                pause();
        }
        return Service.START_NOT_STICKY;
    }


    public void play(String music) throws Exception{
        if (isPause){
            mediaPlayer.reset();
            mediaPlayer.setDataSource(mp3path+music);
            mediaPlayer.prepare();
        }
        mediaPlayer.start();
        isPause = false;
    }

    public void pause(){
        mediaPlayer.pause();
        isPause = true;
    }
}
